<?php

namespace App\Model;

use PhalApi\Model\NotORMModel as NotORM;

class User extends NotORM
{
    public function login($username, $password)
    {
        $psd = md5($password);
        return $this->getORM()->and('username = ?', $username)->and('password = ?', $psd)->fetchAll();
    }

    public function getUserInfo($id)
    {
        // SELECT id FROM `t_user`
        return $this->getORM()->where('id', $id)->fetchOne();
    }

    public function getUserList()
    {
        return $this->getORM()->fetchAll();
    }

    public function getUserInfoByUserName($user_name)
    {
        return $this->getORM()->where('username', $user_name)->fetchOne();
    }

    public function getUserInfoByEmail($email)
    {
        return $this->getORM()->where('email', $email)->fetchOne();
    }

    public function delUserById($userId)
    {
        // DELETE FROM tbl_user WHERE (id = 404);
        // 按条件进行删除，并返回影响的行数
        return $this->getORM()->where('id', $userId)->delete();
    }

    public function insertUserInfo($username, $password, $email, $gender)
    {
        $date = date('Y-m-d h:i:s', time());
        $data = array('role' => 1, 'username' => $username, 'password' => $password, 'email' => $email, 'gender' => $gender, 'createtime' => $date, 'flag' => 2, 'activatecode' => '');
        // INSERT INTO tbl_user (name, age, note) VALUES ('PhalApi', 1, 'framework')
        $orm = $this->getORM();
        $orm->insert($data);

        // 返回新增的ID（注意，这里不能使用连贯操作，因为要保持同一个ORM实例）
        return $orm->insert_id();
    }

    public function likeQueryByUserName($like_username)
    {
        return $this->getORM()->where('username LIKE ?', "%$like_username%")->fetchAll();
    }
}